ColdFusion Article

Caching Queries to Disk or to Memory with ColdFusion

Tyson Vanek

www.coldfusionmaster.com

As most ColdFusion developers are aware, Macromedia ColdFusion provides a built-in mechanism for caching queries. Adding a simple cachedWithin attribute to any cfquery tag in ColdFusion lets you cache a query in memory for a specified time.

If you have ever cached a query using this simple built-in functionality, you are certainly familiar with the challenges and limitations that result from implementing query caching with this method. This type of query caching uses a ColdFusion Administrator setting that limits the maximum number of queries that can exist in the cache at any given time. Additionally, clearing cached queries with this method is a much more difficult task than you would expect. In this article, I explain a custom tag approach for caching queries to memory or to disk, providing more flexibility than built-in ColdFusion methods.

Before continuing any further, note that that there is no substitute for solid database design when it comes to query performance. Often times, you can improve query performance through simple revisions to your SQL statement or taking advantage of the power of your RDBMS by adding database enhancements such as indexes to queried columns. Additionally, the alternative method of caching queries to disk described in this article should not be considered a “best practice,” not to mention the fact that you can add memory cheaply to servers based on current RAM prices. You can, however, easily alter the custom tag to store these cached queries in memory where data access and retrieval is fastest, rather than on disk where you are likely to encounter more overhead.

Consider my method of caching queries to disk (one of the options with my custom tag) as a workaround for certain scenarios you might be facing as a developer. I originally developed the custom tag in this article for a client of mine where, at the time, I did not have the option of altering the database design to improve query performance. Additionally, many of the queries where I applied this custom tag involved complex SQL logic including aggregate functions and a high number of nested inner/left joins across a number of tables. While the resulting final record sets were small to medium size, the query execution was unbearably slow and only got worse with heavier server load. In these cases, I was able to apply this custom tag and drastically improve upon the original execution time of the query. In other cases, however, I found that this custom tag actually executed slower than the original query because the WDDX packets written to disk were so large—as a result of very large record sets or even queries with many large columns. As a developer, always evaluate query performance on a case-by-case basis before and after applying this caching solution.

I recommend reading more about these issues in the Caution When Caching to Disk and Considerations sections later in this article.

Requirements

To complete this tutorial, you will need to install the following software and files:

ColdFusion MX


Dreamweaver MX


Tutorials and sample files:


If you're not already familiar with query caching in ColdFusion, check out Matt Boles' article, Caching in ColdFusion.

A Primer on ColdFusion’s Built-in Query Caching

As I mentioned in the introduction, ColdFusion provides a built-in query caching method. This method uses two simple settings—one that specifies the length of time to cache a query in a tag attribute, and the number of queries that can exist in the cache in the ColdFusion Administrator.

Using the Cfquery Tag's cachedWithin and cachedAfter Attributes

The CFQUERY tag has two optional attributes for caching queries: cachedWithin and cachedAfter. In my experience, developers use the cachedWithin attribute more often than the cachedAfter parameter; the difference between them is minimal.

The cachedWithin attribute represents a period of time for caching a query; you specify the value with the createTimeSpan() function. The first time ColdFusion executes the query with this attribute, it caches and tags the query with the current date/time stamp. After that, each call to the CFQUERY tag evaluates the current date/time and specified time span against the cached query’s date/time stamp. If ColdFusion compares the dates and determines that the cached query has not expired, ColdFusion retrieves the previously cached record from memory and makes it available in the executed page. Of course, if the cached query has expired, then ColdFusion executes the query again and caches the new recordset, tagging it with the current date/time stamp and starting the cycle all over again.

The cachedAfter attribute represents a single date/time after which ColdFusion will cache a query indefinitely. Until the specified date/time passes, ColdFusion will continue to execute this query against the database and return a new recordset. However, once the specified date/time passes, ColdFusion will cache the recordset in memory and use the cache for all subsequent CFQUERY calls.

Using the Maximum Number of Cached Queries Setting

You can find this setting in the ColdFusion Administrator in the Caching section. As you may have guessed by its label, you specify a maximum number of queries that ColdFusion can cache into memory. This setting prevents you from clogging ColdFusion’s memory space with an excessive number of cached queries.

There are a number of pros and cons associated with using this method of query caching.

Pros

  • This caching method is native to ColdFusion and is relatively simple to implement, requiring very little code changes.
  • When you cache queries with this method, you store them in memory, providing the fastest storage and retrieval.

Cons

  • This caching method offers no alternative to storing the cached queries in memory. Because disk space, by comparison, is often more abundant and less expensive than memory, this limits your ability to cache queries on a larger scale.
  • The ColdFusion Administrator setting, Maximum Number of Cached Queries, is a server-wide setting. This means that if you run multiple web applications under a single instance of ColdFusion Application Server, this setting limits the cached queries from all web applications. If your maximum setting is 100 and your first web application has 100 cached queries, then your remaining web applications have no room to store their cached queries without bumping other queries out of the cache.
  • The Maximum Number of Cached Queries value is just that—a number of cached queries. Since you can't predict the recordset sizes that your cached queries can return, it is impossible to estimate the amount of memory that the cached queries might need.
  • When using the cachedWithin parameter, there is no easy way to clear the cached query. Clearing a query when you have used this method requires that you execute the query with a time span of zero (for example, createTimeSpan(0,0,0,0)). Additionally, you cannot clear the cached query without executing it.
  • When using the cachedAfter attribute, there is no easy way to clear the cached query. Clearing a query when you have used this method requires you to execute the query while passing a date/time that has already passed (such as 8/1/1975). Additionally, you cannot clear the cached query without executing it.
  • When you have cached queries using the cachedWithin or cachedAfter attributes, you cannot include cfqueryparam tag calls. Since the cfqueryparam tag offers many useful features for checking and enforcing data types, this is a big drawback. This limitation does not, however, apply to the solution I present on the following pages.

A New Method for Caching Queries

To circumvent the limitations of ColdFusion's built-in query caching method, I developed a custom tag solution that lets you cache queries to memory or to disk. The slight drawback of caching to disk, however, is that caching to disk is often comparatively slower than caching to memory, due to server interfaces and bus speeds.

Introducing the cf_extremeQueryCache Custom Tag

The inspiration for my cf_extremeQueryCache tag came from another great custom tag designed for content caching: cf_superCache. You can download the cf_extremeQueryCache tag from page one of this tutorial. If you have not yet added cf_superCache to your development arsenal, I recommend doing so. You can find the cf_superCache tag by searching the keyword in the Macromedia ColdFusion Exchange. Additionally, Brandon Purcell is currently developing a content caching tag called cf_Accelerate, also inspired by cf_superCache which you can download from his website.

You can use cf_extremeQueryCache around any ColdFusion query in order to cache the query either to memory or to disk. The resulting query cache contains the original query name, the date/time that the cached query will expire, and the returned recordset.

If you're looking for specific details on how the cf_extremeQueryCache tag functions or how to use it, open the tag in Macromedia ColdFusion Studio or in Dreamweaver Code view (or your ColdFusion editor of choice) and spend some time reading the opening comments, all 175 lines of them. The opening comments document the specific functionality of the custom tag, but I will give you a quick overview below.

Implementing cf_extremeQueryCache

Use the following simple steps to install and use the custom tag.

Step 1: Installing the cf_extremeQueryCache Custom Tag

Copy cf_extremeQueryCache.cfm into your ColdFusion custom tag directory at cfusionmx/customtags (or cfusion/customtags directory, if you're using an older version of ColdFusion). Once you copy the extremeQueryCache.cfm file into the customtags directory, all of your ColdFusion web applications can access the cf_extremeQueryCache custom tag. This is a one-time step; you do not need to repeat this step every time you would like to use the custom tag. If you're a JRun user, read all about Creating and Using Custom Tags in the ColdFusion LiveDocs.

Step 2: Identifying a Query for Caching

This step really is subjective, since each developer will have his own opinion on what makes a query a good caching candidate. However, your criteria for selecting a query to cache will be different than it has been in the past since this custom tag can cache any number of queries in memory or onto disk.

Since the ColdFusion Administrator setting, Maximum number cached queries, limits ColdFusion's built-in query caching methods, the criteria for selecting a query to cache previously often met the following conditions:

  • A query used on multiple pages throughout a web application
  • A recordset that does not change frequently
  • A recordset that is the same for all users
  • A query that has a very limited number or no input parameters affecting its recordset

For example, the following query retrieves a list of state names and abbreviations; this is a good candidate for caching through ColdFusion's built-in query caching method.

<cfquery name="qStates" datasource="myDSN">
	select strAbbreviation, strName
	from tblStates
	order by strName
</cfquery>

Conversely, since available server RAM and disk space are the only limitations for the cf_extremeQueryCache custom tag, the criteria for selecting queries to cache becomes much more flexible:

  • A query that executes slowly because of complex SQL logic or because it retrieves a large recordset
  • A query that has input parameters which affect the recordset it returns

For instance, the following query returns all titles that a user has access to and which begin with a letter that the user selected:

<cfquery name="qUserTitles" datasource="myDSN">
	select
		t.uuidTitle,
		t.strTitle
	from
		tblTitle t,
		tblXREF_Title_User xtu,
		tblUser u
	where
		u.user_id = #request.user_id#
	and	u.user_id = xtu.user_id
	and	xtu.title_id = t.title_id
	and	t.strTitle like '#form.strFirstLetter#%'
</cfquery>

Step 3: Creating a Query Caching Directory Structure

Note: Applies to disk caching method only. Skip to Step 4 if you want to cache to memory.

If you choose to have the cf_extremeQueryCache custom tag write cached queries to disk, you must create one or more directories to store the cached queries. I strongly recommend reviewing the Caution When Caching to Disk section of this article before choosing to cache queries to disk.

When using the cf_extremeQueryCache custom tag to cache your queries to disk, I recommend the following:

  1. Create an extremeQueryCache directory outside of your web document root.
  2. Create a subdirectory in the extremeQueryCache directory for each query you plan to cache, preferably using the query's name when naming the subdirectory.

As a security precaution, it's important that you put all your cached queries outside of the web document root if you will be caching security-sensitive information. If users find your query caching directories while poking around your website through their web browser, then they could download the WDDX files, snoop through them, and in short, browse through your database records.

One example of recommended directory structure is as follows. As with the qUserTitles query above, I created two directories:

  • C:\cfusionmx\extremeQueryCache\
  • C:\cfusionmx\extremeQueryCache\qUserTitles

In cases where you are running more than one web application under the same instance of ColdFusion, consider creating directories for each of your applications inside of the extremeQueryCache directory, placing query directories beneath their corresponding application. This will help prevent problems that might arise if you begin caching queries with the same name across multiple applications. In this case, your directory structure would be as follows:

  • C:\cfusionmx\extremeQueryCache\
  • C:\cfusionmx\extremeQueryCache\myAppName\
  • C:\cfusionmx\extremeQueryCache\myAppName\qUserTitles

By default, the cf_extremeQueryCache custom tag will throw an error if the cache directory specified in your tag attribute does not already exist on the file system. Since I included the custom tag file in this article, you could modify the custom tag's code to dynamically create cache directories rather than throw an error. When I created the tag, I wanted explicit control of the location and creation of query caching directories, so I did not build this functionality into the tag.

Step 4: Applying cf_extremeQueryCache to a Query

To use the tag, simply wrap it around the CFQUERY that you would like to cache and specify a few attribute values.

<cf_extremeQueryCache
	queryName=""
	cacheName=""
	cachedWithin=""
	cacheScope|cacheDirectory=""
>
<cfquery name="qUserTitles" datasource="myDSN">
	select
		t.uuidTitle,
		t.strTitle
	from
		tblTitle t,
		tblXREF_Title_User xtu,
		tblUser u
	where
		u.user_id = #request.user_id#
	and	u.user_id = xtu.user_id
	and	xtu.title_id = t.title_id
	and	t.strTitle like '#form.strFirstLetter#%'
</cfquery>
</cf_extremeQueryCache>

queryName

The queryName attribute specifies the name of the query that you are caching between the tag's open and close brackets. In this case, the queryName attribute value is qUserTitles.

<cf_extremeQueryCache
	queryName="qUserTitles"
	...
>
...
</cf_extremeQueryCache>

cacheName

This is the trickiest tag attribute. The cacheName attribute specifies a value that uniquely identifies each possible recordset that the query could return. The simplest way to create a unique value is to create a concatenated string that combines the input parameter values in the query. In the example, there are two input parameters (surrounded by pound signs) that affect the record returned by the query: request.user_id and form.strFirstLetter. Therefore, the cacheName attribute value would be:

<cf_extremeQueryCache
	queryName="qUserTitles"
	cacheName="qUserTitles_#request.user_id#_#form.strFirstLetter#"
	...
>
...
</cf_extremeQueryCache>

cachedWithin

If you're familiar with ColdFusion built-in query caching, then this parameter is no mystery. The value of this parameter specifies how long the server will use the cached query results before running the query again and generating a new cached query.

Determine the cachedWithin value on a case-by-case basis for each query you cache. Consider how often a query's recordset will change. A query that returns state names is unlikely to change, so it's safe to cache the query for a long time. However, a query to an "orders" table for an e-commerce site will likely change all the time as customers submit new orders.

In the qUserTitles example, the query returns a list of titles beginning with a letter that a user selects. Since the titles catalog doesn't change often, caching the query on a daily basis is sufficient.

Set the cachedWithin parameter with a time span using the ColdFusion createTimeSpan() function. Since the function takes parameters of days, hours, minutes, and seconds, you can set the value as follows:

<cf_extremeQueryCache
	queryName="qUserTitles"
	cacheName="qUserTitles_#request.user_id#_#form.strFirstLetter#"
	cachedWithin="#createTimeSpan(1,0,0,0)#"
	...
>
...
</cf_extremeQueryCache>

cacheScope or cacheDirectory

If you are caching the query to memory, use the cacheScope parameter. If you are caching the query to disk, use the cacheDirectory parameter. When using the custom tag, pass only one of these parameters.

cacheScope

This attribute specifies which variable scope to store the cached query in. You can specify a value of server, application, or session. The cached query will be placed in the specified scope as part of a structure called stcExtremeQueryCache.

<cf_extremeQueryCache
	queryName="qUserTitles"
	cacheName="qUserTitles_#request.user_id#_#form.strFirstLetter#"
	cachedWithin="#createTimeSpan(1,0,0,0)#"
	cacheScope="application"
>
...
</cf_extremeQueryCache>
cacheDirectory

This attribute specifies the full directory path of the cache directory.

<cf_extremeQueryCache
	queryName="qUserTitles"
	cacheName="qUserTitles_#request.user_id#_#form.strFirstLetter#"
	cachedWithin="#createTimeSpan(1,0,0,0)#"
	cacheDirectory="c:\cfusionmx\extremeQueryCache\qUserTitles\"
>
...
</cf_extremeQueryCache>

Step 5: Measuring the Impact

At this point, you could save the changes to your code, point your web browser at the page, and fire away. However, I think it's important to take a moment and measure the performance gain you achieve by using this custom tag query caching method. After all, the proof is in the pudding, right? Because I'm certain that pulling a query from the cache will be much faster than executing the query every time, I've added a built-in method for measuring the performance gain, so you can see the difference for yourself.

By simply adding the debugMode attribute with a value of true to the cf_extremeQueryCache tag call, the tag will automatically display a JavaScript alert indicating the execution time (in milliseconds) and whether the server executed the query or retrieved it from cache. Of course, remove the debugMode attribute from your code before releasing your changes to production.

<cf_extremeQueryCache
	queryName="qUserTitles"
	cacheName="qUserTitles_#request.user_id#_#form.strFirstLetter#"
	cachedWithin="#createTimeSpan(1,0,0,0)#"
	cacheScope="application"
	debugMode="true"
>
...
</cf_extremeQueryCache>

Limitations

If you choose to cache queries to memory, I recommend you keep a close watch on your server memory usage once you apply this tag. Since this tag will continue to place more and more cached queries into memory, there is the risk that an extremely large volume of cached queries could drain your server's available RAM and cause overall performance issues for the server. To avoid this, consider running a nightly ColdFusion scheduled task to clear any cached queries from memory (see opening comments of the cf_extremeQueryCache custom tag for details on clearing cached queries).

If you choose to cache queries to disk, consider the following points. While available disk space is the primary limitation of this caching method, there is another limitation not immediately evident. In developing and testing this custom tag, I found another limitation that directly affects the successful implementation of this custom tag when caching queries to disk. While I've not extensively tested it, I believe this issue only affects users running on ColdFusion MX. The limitation has to do with an internal server setting that governs the "entity expansion limit" of ColdFusion. When caching to disk, this custom tag creates WDDX packets storing all the cached query information. If ColdFusion attempts to deserialize a WDDX packet that exceeds the "entity expansion limit," the server throws an error and is unable to deserialize the packet. Because my custom tag uses WDDX packets heavily when caching to disk, with the potential of exceeding the limit, I ran into a problem. Fortunately, I have planned for this particular situation, should you encounter it.

If the cf_extremeQueryCache tag attempts to deserialize a disk-based WDDX packet that exceeds this limit, the tag will throw a custom error message explaining the cause of the error and the steps for increasing the "entity expansion limit," eliminating the problem. Check out Technote 19125: ColdFusion MX 6.1: Error parsing large XML documents, for more information.

If you'd like to eliminate the potential limitation before encountering it, read on. The default value of the "entity expansion limit" is 64000. You can modify this value by adding the following JVM argument in the ColdFusion or JRun Administrator (depending on how you have installed ColdFusion). You must add the argument with the leading "-", preceded by a space, if there are already other JVM arguments present, as follows:

-DentityExpansionLimit=128000

You must decide what the new argument value will be. I simply used 128000 to double the default value.

For this change to take effect, you must restart ColdFusion. If cf_extremeQueryCache continues to throw the error, try a larger value for the argument, restart ColdFusion, and test it again until you eliminate the error.

Caution When Caching to Disk

Developers with more database architecture experience may prefer database alternatives to this method of caching. For example, you might consider writing code that creates, populates, queries, and drops temporary tables in the databasestoring recordsets that require joining or filtering in larger queries. Letting your RDBMS do the heavy database work is often the best decision. However, this approach has a few caveats. If you want to write inline queries in your CFML code to create and drop temporary tables, you must configure your ColdFusion data source connection to use a database user that you set up with permissions to create and drop tables. This creates a bit of a security concern; a hacker could exploit your CFML code through this user and create or drop tables in your database inappropriately. To prevent this potential risk, you could move your create/drop SQL logic into stored procedures and grant execute permissions to your database user. While this is a solid workaround for the security risks I outline above, this method still requires that you have access, permissions, and know-how to create stored procedures in the database. For a primer on creating stored procedures, read Sam Neff's Learning Stored Procedure Basics in ColdFusion MX.

In looking at how my custom tag functions when caching to disk, some would argue that WDDX is an unacceptable means of storing these types of recordsets. WDDX, by design, is meant for exchanging small chunks of information between applications in a common format. However, WDDX also represents a means of creating a text-based snapshot of any ColdFusion object (simple value, query, structure, array, and so forth). Taking that one step further, you can write these text-based snapshots to disk (or memory) and retrieve them later. In most cases, ColdFusion performs very well when reading these files from the server's local disk. The serialization/deserialization of extremely large WDDX packets, however, often results in higher CPU utilization and a performance hit to ColdFusion. In many cases, the cost and execution time of deserializing a very large query result set from a cached WDDX packet loses the race against the execution time of the original query. As a developer, always evaluate query performance on a case-by-case basis before and after applying this caching solution. If you find that executing the original query outperforms deserializing the resulting WDDX packet, you should avoid using this disk-based caching approach and either try memory-based caching or seek other means of boosting your query performance.

The ideal situation for disk-based caching is when a query has many input parameters. Queries with more input parameters have the potential of generating a larger variant of recordsets. For example, consider a single query with input parameters of user_id, category_id, and media_type_id. If you have 5,000 records in your user table, 20 records in your category table, and 4 records in your media_type table, then this query might return 400,000 different recordsets. Now, if you wanted to cache this query into memory, you face the possibility of caching up to 400,000 different recordsets into memory. If each recordset was an average of 5K in size, this means you would use up to 2 GB of your server RAM. Additionally, this is only one queryadditional queries cached to memory would result in an even large number of recordsets stored in memory, chewing up more precious server RAM.

The upside of using my custom tag for disk-based caching is quite simple. By caching to disk, you eliminate concerns of how much memory you will use. Instead, you store cached queries on the server disk, where there is likely to be much more storage space available in comparison to server RAM and, therefore, much less concern over how much space cached queries use.

Considerations

In writing this article, I tested a query that selected the top 1,000 records from a users table containing over 300,000 records while performing many nested inner/left joins to other large database tables. The average execution time without any caching was 12,000 milliseconds (12 seconds). After applying the cf_extremeQueryCache tag to this same query, the average execution time for retrieving this query from the cache was only 600 milliseconds (0.6 seconds). That’s 20 times faster than executing the query without caching. To ColdFusion’s credit, the average execution time for retrieving the cached query when using the built-in cachedWithin method was only 5 milliseconds (0.005 seconds). That’s 2,400 times faster than executing the query normally, and even 120 times faster than using the cf_extremeQueryCache custom tag – as expected since memory access will always be faster than disk access. But, as I explained earlier, the whole point of using this custom tag-based caching solution is to break the limitations of available server memory and the Maximum number of cached queries setting encountered when caching queries with ColdFusion’s built-in caching methods.

Even if you cache a query with an average execution time of four seconds for a 60-second interval, that’s 60 seconds during which the average execution time is likely to be only 0.2 seconds. Anywhere that you can improve the execution time helps in the long run; these improvements magnify as your application receives more traffic and more simultaneous users—every little bit counts.

Conclusion

While ColdFusion natively provides a very effective means of caching queries, there are a number of limitations inherent with this method of query caching. For developers looking to take query caching to the next level and cache higher volumes of queries, queries with larger recordsets, and queries with numerous input parameters with wide variance of resulting recordsets, ColdFusion’s built-in caching methods have limitations. With the cf_extremeQueryCache tag, these limitations are no longer a factor. Whether you’re running a simple query of state names and abbreviations or a complex report evaluating tens of thousands of records, the cf_extremeQueryCache tag can substantially increase performance, contributing to an overall improvement in the speed and reliability of your application.


About the author

Tyson Vanek is an independent consultant specializing in ColdFusion architecture and application development, typically serving as a technical team leader and mentor. With experience dating back to the initial release of ColdFusion v1.0 in 1995, Tyson has worked with ColdFusion on every single web project and application he has been involved in during his nine-year career. In addition to his former role as a Senior Field Consultant working for Allaire and Macromedia, Tyson has worked with a number of large clients including such companies as Footlocker, Lockheed Martin, Abbott Laboratories, University of Virginia, Adelphia, Williams-Sonoma, Chicago Mercantile Exchange, the International Broadcasting Bureau, and Discovery Communications.